package com.powroznik.tracker.client.android;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

public class TrackerService2 extends IntentService {
	public TrackerService2() {
		super("TS2");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		Log.w("TS2", "onHandleIntent");
		if (!bindService(new Intent(this, TrackerService1.class),
				new ServiceConnection() {
					public void onServiceConnected(ComponentName name,
							IBinder service) {
						try {
							TrackerService1 ts1 = ((TrackerService1.TrackerService1Binder) service)
									.getService();
							DeviceConfiguration deviceConfiguration = ts1
									.getDeviceConfiguration(false);
							if (deviceConfiguration != null) {
								scheduleNormal(deviceConfiguration);
							} else {
								scheduleRetry();
							}
						} finally {
							unbindService(this);
						}
					}

					public void onServiceDisconnected(ComponentName name) {
					}
				}, Context.BIND_AUTO_CREATE)) {
			throw new RuntimeException();
		}
	}

	private void scheduleNormal(DeviceConfiguration deviceConfiguration) {
		Log.w("TS2", "scheduleNormal");
		AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		{
			long l0 = System.currentTimeMillis();
			long l1 = l0 % (deviceConfiguration.getDelay2() * 1000);
			long l2 = l0 - l1 + (deviceConfiguration.getDelay2() * 1000);
			alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, l0,
					deviceConfiguration.getDelay2() * 1000, PendingIntent
							.getService(getBaseContext(), 0, new Intent(
									getBaseContext(), TrackerService3.class),
									PendingIntent.FLAG_CANCEL_CURRENT));
		}
		{
			long l0 = System.currentTimeMillis();
			long l1 = l0 % (deviceConfiguration.getDelay3() * 1000);
			long l2 = l0 - l1 + (deviceConfiguration.getDelay3() * 1000);
			alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, l0,
					deviceConfiguration.getDelay3() * 1000, PendingIntent
							.getService(getBaseContext(), 1, new Intent(
									getBaseContext(), TrackerService4.class),
									PendingIntent.FLAG_CANCEL_CURRENT));
		}
	}

	private void scheduleRetry() {
		Log.w("TS2", "scheduleRetry");
		AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		{
			{
				long l0 = System.currentTimeMillis();
				long l1 = l0 % (60 * 1000);
				long l2 = l0 - l1 + (60 * 1000);
				alarmManager.set(AlarmManager.RTC_WAKEUP, l0, PendingIntent
						.getService(getBaseContext(), 2, new Intent(
								getBaseContext(), TrackerService2.class),
								PendingIntent.FLAG_CANCEL_CURRENT));
			}
		}
	}
}
